package com.lzy.cloud.payment.component.pay;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Properties;

/**
 * 
 * Description:支付请求处理类父类
 * 
 * @author lc Create Date Time:Mar 22, 201711:35:24 AM
 */
public abstract class PayRequestHandler {
	private static final Logger LOGGER = LoggerFactory.getLogger(PayRequestHandler.class);

	private static final String PAYMENT_PROPERTIES_LOCATION = "payment.properties";

	private static Properties payProp = null;
	/**
	 * 同步:通知url。 例子：比如web端支付宝收银台完成后，调用该url，返回自己网站
	 */
	private static String return_url = null;

	/**
	 * 异步:通知url。 例子：比如支付异常，可以走这里
	 */
	private static String notify_url = null;
	/**
	 * 是否需要构建请求表单：默认不需要
	 */
	private static boolean v = true;

	/**
	 * 初始化加载return.url和notify.url
	 */
	static {
		try {
			// payProp = PropertiesUtil
			// .loadProperties(PAYMENT_PROPERTIES_LOCATION);
		} catch (Exception e) {
			LOGGER.error("初始化payment.properties文件失败!", e);
		}
	}

	public final String forwardToPay(PayInfoWrapper payInfoWrapper) {
		Map<String, String> params = buildPayParam(payInfoWrapper);
		String returnUrl = payProp.getProperty(return_url);
		String notifyUrl = payProp.getProperty(notify_url);
		if (StringUtils.isBlank(notifyUrl))
			return null;
		params.put("return_url", returnUrl);
		params.put("notify_url", notifyUrl);
		doSign(params);
		return buildPaymentString(params);

	}

	protected String buildPaymentString(Map<String, String> params) {
		StringBuilder sbHtml = new StringBuilder();
		sbHtml.append("<form id=\"payForm\" name=\"payForm\" action=\""
				+ getPaymentURL() + "\" " + "method=\"get\">");
		for (Map.Entry<String, String> entry : params.entrySet()) {
			sbHtml.append("<input type=\"hidden\" name=\"" + entry.getKey()
					+ "\" value=\"" + entry.getValue() + "\"/>");
		}
		sbHtml.append("<input type=\"submit\" value=\"" + "确认"
				+ "\" style=\"display:none;\"></form>");
		sbHtml.append("<script>document.forms['payForm'].submit();</script>");
		return sbHtml.toString();
	}

	/**
	 * 携带参数，由子类实现
	 * 
	 * @param payInfoWrapper
	 * @return
	 */
	protected abstract Map<String, String> buildPayParam(
			PayInfoWrapper payInfoWrapper);

	/**
	 * 
	 * @return
	 */
	protected abstract String getPaymentURL();

	/**
	 * 签名，并追加签名参数，由子类实现
	 * 
	 * @return
	 */
	protected abstract void doSign(Map<String, String> params);

}
